package com.SouthernWall_404.age_tool.common.API.Capability;

import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraftforge.common.util.INBTSerializable;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class TriggersCap implements INBTSerializable<CompoundTag> {

    public Map<UUID,Boolean> allRemoteIdState=new HashMap<>();
    public static final String AMOUNT_TAG ="size";
    public static final String STATE_TAG="state";
    public static final String REMOTE_TAG="remote";
    public static final String UUID_TAG="id";
    public static final String BOOLEAN_TAG ="boolean";


    public boolean isActive(UUID uuid)

    {
        boolean isActive=false;

        if(allRemoteIdState.containsKey(uuid))
        {
            isActive=allRemoteIdState.get(uuid);
        }
        return isActive;
    }
    public boolean available(UUID uuid)
    {
        return setAvailability(uuid,true);
    }
    public boolean inavailable(UUID uuid)
    {
        return setAvailability(uuid,false);
    }
    public boolean setAvailability(UUID uuid,boolean b)
    {
        if(allRemoteIdState.containsKey(uuid))
        {
            allRemoteIdState.put(uuid,b);
            return true;
        }
        else
        {
            return false;
        }

    }
    public void addRemote(UUID uuid)
    {
        allRemoteIdState.put(uuid,false);
    }
    public void removeRemote(UUID uuid)
    {
        allRemoteIdState.remove(uuid);
    }

    @Override
    public CompoundTag serializeNBT() {
        CompoundTag nbt = new CompoundTag();
        CompoundTag remotePack=new CompoundTag();
        ListTag statePack=new ListTag();
        for (Map.Entry<UUID,Boolean> entry : allRemoteIdState.entrySet()) {
            CompoundTag entryTag = new CompoundTag();
            entryTag.putUUID(UUID_TAG, entry.getKey());
            entryTag.putBoolean(BOOLEAN_TAG, entry.getValue());
            statePack.add(entryTag);
        }
        remotePack.put(STATE_TAG,statePack);
        remotePack.putInt(AMOUNT_TAG,statePack.size());
        nbt.put(REMOTE_TAG,remotePack);
        return nbt;
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        if(nbt.contains(REMOTE_TAG))
        {
            CompoundTag remotePack=nbt.getCompound(REMOTE_TAG);
            if(remotePack.contains(AMOUNT_TAG)&&remotePack.contains(STATE_TAG))
            {
                int size=remotePack.getInt(AMOUNT_TAG);
                ListTag remoteList=remotePack.getList(STATE_TAG, Tag.TAG_COMPOUND);
                for (int i = 0; i < remoteList.size(); i++) {
                    CompoundTag entryTag = remoteList.getCompound(i);
                    UUID uuid=entryTag.getUUID(UUID_TAG);
                    boolean b=entryTag.getBoolean(BOOLEAN_TAG);
                    allRemoteIdState.put(uuid,b);
                }
            }
        }
    }
}
